package org.jeecg.modules.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiCallBackGetCallBackFailedResultRequest;
import com.dingtalk.api.response.OapiCallBackGetCallBackFailedResultResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.RoleInfo;
import org.jeecg.modules.config.Constant;
import org.jeecg.modules.service.CallbackService;
import org.jeecg.modules.service.IDiyProfessorInfoService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author ZhangHaoyu
 * @description
 * @date 2020/7/8 21:39
 */
@Slf4j
public class TimingTask implements Job {

    @Autowired
    IDiyProfessorInfoService diyProfessorInfoService;

    @Autowired
    CallbackService callbackService;

    @Autowired
    ISysBaseAPI iSysBaseAPI;
    /**
     * 每分钟获取失败的回调list进行判断
     *
     * @author ZhangHaoyu
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 调用这个
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/call_back/get_call_back_failed_result");
        OapiCallBackGetCallBackFailedResultRequest request = new OapiCallBackGetCallBackFailedResultRequest();
        request.setHttpMethod("GET");
        // 获取token
        String token = AccessTokenUtil.getToken();

        OapiCallBackGetCallBackFailedResultResponse response = null;
        try {
            response = client.execute(request,token);
            // 获取response的失败的list集合
            List<OapiCallBackGetCallBackFailedResultResponse.Failed> list = response.getFailedList();

            if(list!=null){
                // 遍历集合
                for (OapiCallBackGetCallBackFailedResultResponse.Failed failed :
                        list) {
                    // 获取bpmsChange
                    if (failed.getBpmsInstanceChange()!=null){
                        String bpmsInstanceChange = failed.getBpmsInstanceChange();

                        log.info("bpmsInstanceChange = {}",bpmsInstanceChange);
                        // 进行剪切操作
                        String[] str = bpmsInstanceChange.split("processInstanceId=");
                        String[] split = str[1].split(",", 2);
                        //获取processInstanceId
                        String processInstanceId = split[0];
                        str = bpmsInstanceChange.split("processCode=");
                        split = str[1].split(",", 2);
                        // 获取模板id
                        String processCode = split[0];
                        // 调用方法获取信息
                        getInstanceInfo(processInstanceId,processCode);
                    }
                }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据审批实例id和审批模板id进行相关操作
     * @param processInstanceId
     * @param processCode
     */
    public void getInstanceInfo(String processInstanceId,String processCode) {

        if (Constant.PROCESS_CODE.equals(processCode)){
            // 验证是不是人员申请表审批模板id
            failProfessorInfoToSave(processInstanceId);
        }

        if (Constant.QUIT_PROCESS_CODE.equals(processCode)){
            // 专家离职
            failProfessorQuit(processInstanceId);
        }

    }

    /**
     * 网络问题导致离职同意失败的操作
     * @param processInstanceId
     */
    public void failProfessorQuit(String processInstanceId){
        // 调用方法获取审批实例内容
        String body = callbackService.getInfoById(processInstanceId);
        // 转为json对象
        JSONObject object = JSON.parseObject(body);
        String process_instance = object.getString("process_instance");
        log.info(process_instance);
        JSONObject object1 = JSON.parseObject(process_instance);
        // 获取申请人id
        String originator_userid = object1.getString("originator_userid");
        // 获取tasks  是一个数组
        String tasks = object1.getString("tasks");
        // 转换遍历获取task_result
        JSONArray array = JSON.parseArray(tasks);
        for (int i = 0; i<array.size();i++){
            JSONObject arrObj = array.getJSONObject(i);
            String task_result = arrObj.getString("task_result");
            log.info(task_result);
            // 判断task_result状态
            if("AGREE".equals(task_result)){
                // 删除专家信息表中内容
                diyProfessorInfoService.deleteProfessorByDingId(originator_userid);
                // 获得unionId
                String unionId = callbackService.getUnionIdByUserIdFromDB(originator_userid);
                // 删除专家的角色和登录信息
                diyProfessorInfoService.deleteProfessorByUnionId(unionId);

                log.info("离职删除档案");
            }
        }
    }


    /**
     * 专家信息提交审核模板失败之后的处理
     * @param processInstanceId
     */
    public void failProfessorInfoToSave(String processInstanceId){
        // 调用方法获取审批实例内容
        String body = callbackService.getInfoById(processInstanceId);
        // 转为json对象
        JSONObject object = JSON.parseObject(body);
        String process_instance = object.getString("process_instance");
        log.info(process_instance);
        JSONObject object1 = JSON.parseObject(process_instance);
        // 获取tasks  是一个数组
        String tasks = object1.getString("tasks");
        // 转换遍历获取task_result
        JSONArray array = JSON.parseArray(tasks);
        for (int i = 0; i<array.size();i++){
            JSONObject arrObj = array.getJSONObject(i);
            String task_result = arrObj.getString("task_result");
            // 判断task_result状态
            if("AGREE".equals(task_result)){
                // 如果同意，调用方法同步到数据库
                JSONObject object2 = JSON.parseObject(process_instance);
                // 获取申请人的dingID
                String originator_userid = object2.getString("originator_userid");
                log.info(originator_userid);
                try {
                    //更新用户部门
                    UserUtil.updateDingUser(originator_userid);
                    // 同步信息到数据库
                    diyProfessorInfoService.saveByJsonObj(object,originator_userid);
                    // 获取专家角色id
                    RoleInfo roleInfo = iSysBaseAPI.getRoleInfoByCode("professor");
                    String roleId = roleInfo.getId();
                    // 根据userid获取id，通过unionid转换
                    String uid = callbackService.getUnionIdByUserId(originator_userid);
                    log.info(" uid is {} ",uid);
                    // 更新为正式专家
                    Integer integer = iSysBaseAPI.addRole(uid, roleId);
                    log.info("更新专家的角色为正式专家----- {} ",integer==1?"成功":"失败");
                } catch (ApiException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
